import React, { useState, useEffect,useRef } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,Input,Select,Divider,notification,Modal} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries} from 'redux/action'
import './index..scss'

import {queryPageUserTheme,userThemeAdd,userThemeUpdateBatch} from 'api/index'
import classNames from "classnames";



const { Search } = Input;

// 新增编辑弹框
const AddTheme = (props) =>{
  const {isModalVisible, setIsModalVisible,dictionaries,userName,form} = props

  const loading = useRef(false)

  // 新增表单
const newWordItem = [
  {label: '列表名称',type:'input', name: 'rankName' , span: 12 ,rules:[
    {
      required: true,
      message: '请输入单词名称'
    },
  ]},
  {label: '用户级别', name: 'levelAppId', span: 12 ,rules:[
    {
      required: true,
      message: '请选择用户级别'
    },
  ],render:()=>{
    return   <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择用户级别'}
    options={dictionaries.LevelApp}
  >
  </Select>
  }}
]

  const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    form.validateFields().then(async()=>{
       

       const res = await userThemeAdd(form.getFieldValue())

       notification.success({
          message: res.message,
          description: '操作人：' + userName,
          duration: 2
        });
      
      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
  };

  const handleCancel = () => {
    form.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={950} title={form.getFieldValue().id?'编辑课包':'新增课包'} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={form} labelCol={5} formItem={newWordItem} />
   </Modal>
} 


function UserThemeLibrary(props){
const {dictionaries} = props
// 数据
const [loading,setLoading] = useState(false) //加载
const [total,setTotal] = useState(0) //总数量
const [isModalVisible, setIsModalVisible] = useState(false) // 新增编辑弹框
const [form] = Form.useForm();//搜索列表
const [formItemUser] = Form.useForm();//搜索列表


// 表单数据
const formItem = [
  {label: '课表级别', name: 'levelAppId', span: 6 ,render: () => {
    return <Select
    allowClear
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择题型'}
    options={dictionaries.LevelApp}
  >
  </Select>
}},
{label: '创建人', name: 'createBy',  span: 6 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择创建人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
  {label: '', name: 'rankName' , span: 6,render: () => {
    return   <Search placeholder="请输入关键词搜索" onSearch={getNewList} enterButton />
} }
]
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = [
      {title: '名称', dataIndex: 'rankName', key: 'rankName', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link"  onClick={()=>goThemeList(record)}>
          {text}
       </div>
     }},
      {title: '节数', dataIndex: 'count', key: 'count', align: 'center'},
      {title: '用户级别', dataIndex: 'levelAppName', key: 'levelAppName', align: 'center'},
      {title: '创建人', dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
     }},
      {title: '更新人', dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
     }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
      {title: '编辑', dataIndex: 'active', key: 'active', align: 'center',width:120,render:(text, record) => {
        return  <>
         <span className="text-link" onClick={()=>editTheme(record)}>编辑</span>&nbsp;&nbsp;&nbsp;&nbsp;
         <span className="text-link" onClick={()=>delTheme(record)}>删除</span>
        </>
      }}
]



// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='plan/userCounrseSubject')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='plan/userCounrseSubject')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()

  
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{
  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('plan/userCounrseSubject',data) 

    const initialData = async () => {

      const {
        levelAppId,
        rankName,
        createBy
      } = form.getFieldValue()
      

      const params = {
        currPage:value&&value.pageSize?value.current:pagination.current,
        pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
        createBy,
        levelAppId,
        rankName,
      }

       
     
        const res = await queryPageUserTheme(params)
        const data = res.result.records || []

        setDataSource(data)
  
        setTotal(res.result.total)
    

        setLoading(false)
    
    }
  
    initialData()
    }

// 2.新增课包
const addNewUserTheme = () => {
  formItemUser.setFieldsValue({id:''})
  setIsModalVisible(true)
}

// 3.编辑课包
const editTheme = (value) => {
  formItemUser.setFieldsValue(value)
  setIsModalVisible(true)
}

// 4.删除课包
const delTheme = async(value) => {
    await userThemeUpdateBatch([{
    id: value.id,
    status: 0
   }])
   notification.success({
    message: '移除成功',
    description: '操作人：' + props.userInfo.user.userName,
    duration: 1.5
  });

  getNewList()

}

// 5.前往详情
const goThemeList = (value) => {
  console.log(value);

  props.history.push('/view/plan/userCounrseSubjectList?id=' + value.id + '&levelAppId=' + value.levelAppId +'&levelAppName=' + value.levelAppName)
  props.addRouter({
    menuName:'用户主题课列表',url:'plan/userCounrseSubjectList?id=' + value.id + '&levelAppId=' + value.levelAppId +'&levelAppName=' + value.levelAppName
  })
}

return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={formItem}/>

       {/* 操作按钮 */}
       <div className="operate-btn">
       <div>
         <Button  onClick={addNewUserTheme} type='primary' className='animate__animated animate__fadeInLeft'>新增课包</Button>
       </div>
    </div>

    <Divider />

    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={false}
     height={320}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

     {/* 新增编辑弹框 */}
     <AddTheme form={formItemUser} dictionaries={dictionaries} getNewList={getNewList} userName={props.userInfo.user.userName}  isModalVisible={isModalVisible} setIsModalVisible={setIsModalVisible}></AddTheme>
 
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(UserThemeLibrary)
